package menus_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
)

func (MenusApi) MenusDetailView(c *gin.Context) {
	id := c.Param("id")
	// 先查询菜单
	var menuList models.MenuModel
	err := common.DB.Take(&menuList, id).Error
	if err != nil {
		http.FailWithMessage("菜单不存在", c)
		return
	}
	// 关联查询表
	var menuBanners []models.MenuBannerModel
	common.DB.Preload("BannerModel").Order("sort DESC").Find(&menuBanners, "menu_id = ?", id)
	// 组合数据
	// 增加 banner 只声明, 不赋值如果是引用类型就返回null 解决 banners字段返回为 null var banners []banner , 使用下面代码就能解决 null banners := make([]banner, 0)
	banners := make([]banner, 0)
	for _, menuBanner := range menuBanners {
		if menuList.ID != menuBanner.MenuID {
			continue
		}
		banners = append(banners, banner{
			ID:   menuBanner.BannerID,
			Path: menuBanner.BannerModel.Path,
		})
	}
	menu := menuResponse{
		MenuModel: menuList,
		Banners:   banners,
	}
	http.IsOkWithData(menu, c)
}
